#include "script/glue/LuaGlue.h"

#include <OgreColourValue.h>

namespace LuaGlue
{

	int ColourValue::create(lua_State *L)
	{
		double r,g,b,a;
		switch(lua_gettop(L))
			{
			case 1:
				if(!lua_istable(L, 1))
					{
						luaL_typerror(L, 1, "table");
						break;
					}
				lua_gettable_number_i(L, r, 1);
				lua_gettable_number_i(L, g, 2);
				lua_gettable_number_i(L, b, 3);
				lua_gettable_number_i(L, a, 4);
				break;

			case 4:
				r = luaL_checknumber(L, 1);
				g = luaL_checknumber(L, 2);
				b = luaL_checknumber(L, 3);
				a = luaL_checknumber(L, 3);
				break;
			default:
				luaL_error(L, "Incorrect number of arguments for function");
				return 0;
				break;
			}

		Ogre::ColourValue *c = new Ogre::ColourValue(r,g,b,a);

		Wrapper<ColourValue>::Instance(L, (void*)c);

		return 1;
	}

	int ColourValue::tostring (lua_State *L)
	{
		Ogre::ColourValue *c = unwrap<Ogre::ColourValue>(L, 1);
		char buff[255];
		sprintf(buff, "%f,%f,%f,%f", c->r, c->g, c->b, c->a);
		lua_pushfstring(L, "ColourValue (%s)", buff);
		return 1;
	}

	int ColourValue::get( lua_State *L )
	{
		Ogre::ColourValue *c = unwrap<Ogre::ColourValue>(L, 1);
		const char *key = luaL_checkstring(L, 2);

		if(Wrapper<ColourValue>::Method(L, key)) return 1;

		if (strcmp(key, "r") == 0)
			lua_pushnumber(L, c->r);

		if (strcmp(key, "g") == 0)
			lua_pushnumber(L, c->g);

		if (strcmp(key, "b") == 0)
			lua_pushnumber(L, c->b);

		if (strcmp(key, "b") == 0)
			lua_pushnumber(L, c->a);

		return 1;
	}

	int ColourValue::set( lua_State *L )
	{
		Ogre::ColourValue *c = unwrap<Ogre::ColourValue>(L, 1);
		const char *key = luaL_checkstring(L, 2);
		int val = luaL_checknumber (L, 3);

		if (strcmp(key, "r") == 0)
			c->r= val;

		if (strcmp(key, "g") == 0)
			c->g= val;

		if (strcmp(key, "b") == 0)
			c->b= val;

		if (strcmp(key, "a") == 0)
			c->a= val;

		return 1;
	}

	int ColourValue::add(lua_State *L)
	{
		Ogre::ColourValue *c1 = unwrap<Ogre::ColourValue>(L, 1);
		Ogre::ColourValue *c2 = unwrap<Ogre::ColourValue>(L, 2);
		Ogre::ColourValue *r = new Ogre::ColourValue(*c1 + *c2);
		Wrapper<ColourValue>::Instance(L, (void*)r);
		return 1;
	}

}

DECLARE(ColourValue)
META(ColourValue)
{"__tostring", LuaGlue::ColourValue::tostring},
{"__index",    LuaGlue::ColourValue::get},
{"__newindex", LuaGlue::ColourValue::set},
{"__add", 	   LuaGlue::ColourValue::add},
METHODS(ColourValue)
END
